<template>
  <div>
    <div>
      <el-divider content-position="left">接口查询</el-divider>
      <el-form ref="form" :model="form" label-width="80px" class="">
        <el-form-item class="form-item" label="接口名称">
          <el-input v-model="form.name" placeholder="接口名称"></el-input>
        </el-form-item>
        <el-form-item class="form-item" label="接口路径">
          <el-input v-model="form.url" placeholder="接口url"></el-input>
        </el-form-item>
        <el-form-item class="form-item" label="请求方式" content="">
          <el-select v-model="form.method" placeholder="请选择">
            <el-option label="POST" value="POST"></el-option>
            <el-option label="GET" value="GET"></el-option>
            <el-option label="DELETE" value="DELETE"></el-option>
            <el-option label="PUT" value="PUT"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="form-item">
          <el-button class="form-btn" type="primary" @click="onQuery">查询</el-button>
          <el-button class="form-btn" @click="clearQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-divider content-position="left">接口列表</el-divider>
    <!--增改删导出-->
    <el-row>
      <el-button class="tag-btn" type="success" plain @click="addItfVisible = true">新增</el-button>
      <el-button class="tag-btn" type="warning" plain @click="modifyItf('modify')">修改</el-button>
      <el-button class="tag-btn" type="danger" plain @click="delItf('del')">删除</el-button>
      <el-button class="tag-btn" type="info" plain @click="outputItfData">导出</el-button>
      <template>
        <el-input-number class="curPageCounter" @change="handleCurrentChange" v-model="curPage" :min="1" :max="pages" label="描述文字"></el-input-number>
      </template>
    </el-row>

    <!--列表-->
    <template>
      <el-table
        class="interface-table"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column
          align="center"
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          align="center"
          prop="id"
          label="接口ID"
          width="70">
        </el-table-column>
        <el-table-column
          align="center"
          prop="itfName"
          label="接口名称"
          width="150">
        </el-table-column>
        <el-table-column
          align="center"
          prop="itfUrl"
          label="接口路径"
          width="150">
        </el-table-column>
        <el-table-column
          align="center"
          prop="itfMethod"
          label="请求方式"
          width="150">
        </el-table-column>
        <el-table-column
          align="center"
          prop="createTime"
          label="创建时间"
          width="200">
        </el-table-column>
        <el-table-column
          align="center"
          prop="updateTime"
          label="更新时间"
          width="200">
        </el-table-column>
        <el-table-column
          align="center"
          label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-pagination
          background
          class="interpage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="curPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </template>
    <!--新增接口对话框-->
    <el-dialog
      title="新增接口规则"
      :visible.sync="addItfVisible"
      width="40%">
      <el-form label-width="80px">
        <el-form-item label="接口名称">
          <el-input v-model="addItfForm.name" placeholder="请输入接口名称"></el-input>
        </el-form-item>
        <el-form-item label="接口URL">
          <el-input v-model="addItfForm.url" placeholder="请输入接口路径"></el-input>
        </el-form-item>
        <el-form-item label="接口方式">
          <el-select v-model="addItfForm.method" placeholder="请选择">
            <el-option label="GET" value="GET"></el-option>
            <el-option label="POST" value="POST"></el-option>
            <el-option label="PUT" value="PUT"></el-option>
            <el-option label="DELETE" value="DELETE"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="响应规则">
          <el-input
            style="font-size: 16px;"
            type="textarea"
            :rows="5"
            placeholder='请输入JsonArray响应参数规则，示例：[{"id": "$integer", "name": "$word"}]'
            v-model="addItfForm.respParams">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addItfVisible = false">取 消</el-button>
        <el-button type="primary" @click="addItf">提交</el-button>
      </span>
    </el-dialog>

    <!--修改接口对话框-->
    <el-dialog
      title="修改接口规则"
      :visible.sync="modifyItfVisible"
      width="40%">
      <el-form label-width="80px">
        <el-form-item label="接口名称">
          <el-input v-model="modifyItfForm.name" :placeholder="modifyItfForm.name" disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="接口URL">
          <el-input v-model="modifyItfForm.url" :placeholder="modifyItfForm.url" disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="接口方式">
          <el-select v-model="modifyItfForm.method" :placeholder="modifyItfForm.method" disabled="disabled">
            <el-option label="GET" value="GET"></el-option>
            <el-option label="POST" value="POST"></el-option>
            <el-option label="PUT" value="PUT"></el-option>
            <el-option label="DELETE" value="DELETE"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="响应规则">
          <el-input
            type="textarea"
            :rows="5"
            placeholder="请输入响应参数规则"
            v-model="modifyItfForm.respParams" :placeholder="modifyItfForm.respParams">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyItfVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitModifyItf">提交</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  export default {
    name: "interface",
    props: {
    },
    data() {
      return {
        /*查询表单*/
        form: {
          name: '',
          url: '',
          method: '',
        },
        /*接口列表*/
        tableData: [],
        multipleSelection: [],
        /*分页*/
        curPage: 1,
        size: 5,
        total: 0,
        pages: 0,
        addItfVisible: false,
        addItfForm: {
          name: '',
          url: '',
          method: '',
          respParams: [],
        },
        modifyItfVisible: false,
        modifyItfForm: {
          name: '',
          url: '',
          method: '',
          respParams: '',
        },
      }
    },
    mounted: function(){
      this.queryItfList();
    },
    computed: {
      headers() {
        return {
          Authentication: this.$store.state.token,
          RefreshToken: this.$store.state.refresh_token
        };
      }
    },
    methods: {
      resetInterfaceQueryForm(form) {
        this.$refs[form].resetFields();
      },
      //接口查询
      onQuery(){
        this.queryItfList();
        console.log("查询成功！");
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleEdit(index, row) {
        console.log(index, row);
        this.modifyItf(row.id);
      },
      handleDelete(index, row) {
        console.log(index, row);
        if(confirm("确认要删除？")){
          this.delItf(row.id);
        };
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.size = val;
        this.queryItfList();
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.curPage = val;
        this.queryItfList();
      },
      //提交新增接口
      addItf(){
        console.log("提交成功！");
        //校验响应参数规则是否是JSONArray
        this.checkJsonArray(this.addItfForm.respParams);
        this.$http.post("/mock/interface/add", {
          "itfName": this.addItfForm.name,
          "itfUrl": this.addItfForm.url,
          "itfMethod": this.addItfForm.method,
          "respParams": JSON.parse(this.addItfForm.respParams)
        }).then(resp => {
          if(resp.data.errCode === 200){
            this.$message.success("新增成功！");
            this.addItfVisible = false;
            this.queryItfList();
            this.clearAddItfForm();
          }
        });
      },
      //修改按钮(oprNum操作数为1时则为“修改”功能，否则为编辑)
      modifyItf(oprNum){
        //修改
        if(oprNum === 'modify'){
          //判断是否已选择
          if(this.multipleSelection.length !== 1){
            this.$message.error("请选择一条接口数据！");
            return;
          }
          this.modifyItfVisible = true;
          this.multipleSelection.forEach(t => {
            this.queryOne(t.id);
          });
        }else { //编辑
          this.queryOne(oprNum);
        }
      },
      //删除
      delItf(oprNum){
        //删除按钮
        if(oprNum === 'del'){
          //判断是否已选择
          if(this.multipleSelection.length !== 1){
            this.$message.error("请选择一条接口数据！");
            return;
          }
          if(confirm("确认要删除？")){
            this.multipleSelection.forEach(t => {
              this.submitDelItf(t.id);
            });
          }
        }else { //操作中的删除
          this.submitDelItf(oprNum);
        }
      },

      //修改接口
      submitModifyItf(){
        this.$http.post("/mock/interface/mod", {
          "itfName": this.modifyItfForm.name,
          "itfUrl": this.modifyItfForm.url,
          "itfMethod": this.modifyItfForm.method,
          "respParams": JSON.parse(this.modifyItfForm.respParams)
        }).then(resp => {
          if(resp.data.errCode === 200){
            this.$message.success("接口修改成功！");
            this.modifyItfVisible = false;
            this.queryItfList();
          }
        })
      },

      //导出接口数据
      outputItfData(){
        //判断是否已选择
        if(this.multipleSelection.length === 0){
          this.$message.error("请选择一条接口数据！");
          return;
        }
        this.$http({
          method: "post",
          url: "/mock/interface/export",
          data: this.multipleSelection,
          responseType: "blob"
        }).then(resp => {
          let url = window.URL.createObjectURL(new Blob([resp.data])); //创建blob,设置文件类型
          let a = document.createElement('a'); //创建a标签
          a.download = "接口数据表.xls"; //指定文件名
          a.style.display = 'none';
          a.href = url; //创建url
          a.click(); //click事件触发下载
          // URL.revokeObjectURL(a); //释放内存
        });
      },

      //查询接口列表
      queryItfList(){
        this.$http.post("/mock/interface/query/list", {
          "curPage": this.curPage,
          "size": this.size,
          "itfName": this.form.name,
          "itfUrl": this.form.url,
          "itfMethod": this.form.method
        }).then(resp => {
          if (resp.data.errCode === 200){
            this.total = resp.data.data.totals;
            this.pages = resp.data.data.pages;
            this.tableData = resp.data.data.data;
          }
        })
      },

      //查询单个接口
      queryOne(id){
        this.$http.post("/mock/interface/query/"+id).then(resp => {
          if(resp.data.errCode === 200){
            this.modifyItfVisible = true;
            this.modifyItfForm.name = resp.data.data.itfName;
            this.modifyItfForm.url = resp.data.data.itfUrl;
            this.modifyItfForm.method = resp.data.data.itfMethod;
            this.modifyItfForm.respParams = JSON.stringify(resp.data.data.respParams);
          }
        })
      },

      //删除单个接口
      submitDelItf(id){
        this.$http.post("/mock/interface/del/"+id).then(resp => {
          if(resp.data.errCode === 200){
            this.$message.success("删除成功！");
            this.queryItfList();
          }
        })
      },

      //清空查询条件
      clearQuery(){
        this.form = {
          name: '',
          url: '',
          method: ''
        }
      },
      clearAddItfForm(){
        this.addItfForm = {
          name: '',
          url: '',
          method: '',
          respParams: [],
        }
      },
      checkJsonArray(respParams) {
        if(respParams === '' || respParams === null){
          this.$message.error("请输入正确格式的响应规则！");
          return;
        }

      }
    }
  }
</script>

<style scoped>
  .form-item{
    margin-left: 20px;
    width: 20%;
    display: inline-block;
  }
  .form-btn{
    position: relative;
    left: -60px;
  }
  .tag-btn{
    margin-left: 20px;
  }
  .interface-table{
    position: relative;
    left: 20px;
    top:10px;
  }
  .interpage{
    margin-top: 20px;
    margin-left: 20px;
    margin-bottom: 20px;
  }
  .curPageCounter{
    float: right;
    right: 40px;
  }
</style>
